function getError(option, xhr) {
  const msg = `cannot complete ${option.action} ${xhr.status}`;
  const err = new Error(msg);
  err.status = 'status:'+xhr.status;
  err.xhr = xhr;
  err.method = 'post';
  err.url = option.action;
  return err;
}

function getBody(xhr) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (e) {
    return text;
  }
}

export default function upload(option) {
  if (typeof XMLHttpRequest === 'undefined') {
    return;
  }
  const xhr = new XMLHttpRequest();
  if (xhr.upload) {
    xhr.upload.onprogress = (e) => {
      if (option.onProgress){
        option.onProgress(e);
      }
    };
  }

  xhr.onerror = (e) => {
    option.onError(getError(option,xhr));
  };

  xhr.onload = () => {
    if (xhr.status !== 200) {
      console.log(getError(option, xhr));
      option.onError(getError(option, xhr), getBody(xhr));
      return;
    }

    option.onSuccess(getBody(xhr));
  };
  xhr.open(option.method, option.action, true);
  if (option.header) {
    for (const key in option.header) {
      xhr.setRequestHeader(key, option.header[key]);
    }
  }
  // xhr.setRequestHeader('Content-Type','multipart/form-data');
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  if (option.contentType){
    xhr.setRequestHeader('Content-Type',option.contentType);
  }
  option.xhr = xhr;
  xhr.send(option.data);
  // return xhr;
}
